<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Controllers\Controller;
use Mockery\Exception;
use Overtrue\EasySms\EasySms;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Illuminate\Support\Facades\Log;
class CalendarController extends Controller
{
    private $company_id;
    private $user;
    private $role_flag;
    public function __construct()
    {
        $this->deviceType = $this->getDevice();
        if (\Auth::guard('api')->check()) {
            $user = \Auth::guard('api')->user();
            $data = User::find($user->id);
            if($this->deviceType){
//                PC
                $this->company_id = $data->company_id;
                $this->user = $data;
            }else{
//                APP
                $this->company_id = $data->appcompany_id;
                $this->user = $data;
                $this->user->company_id = $data->appcompany_id;
            }
            $company = \App\Models\Company::find($this->user->company_id);
            if(!empty($company)){
                $this->role_flag = $company->role_flag;
            }
        }
    }
    /**
     * 日历列表
     * @param  $id    [用户ID]
     * @param  $return  json
     */
    public function calendarList(Request $request){
        $userInfo = $this->user;
        $uid  = $userInfo->id;
        $time = $request->input('time') ?? time();
        $weekTime = $request->input('weekTime');
        $weekEnd = strtotime('+7 days',$weekTime)-1;
        $startTime = strtotime(date('Y-m-d',$time));
        if(!empty($weekTime)){
            $weekInfo = DB::table('calendar')
                ->where('owner_id',$uid)
                ->whereBetween('start_time', [$weekTime,$weekEnd])
                ->select(DB::raw("from_unixtime(start_time,'%Y/%m/%d') as time"), DB::raw("count(*) as count"))
                ->groupBy(DB::raw("from_unixtime(start_time,'%Y/%m/%d')"))
                ->get();
            for($i=0;$i<7;$i++){
                $weeks['time'][$i] = date('Y/m/d',strtotime("+$i days",$weekTime));
                $weeks['list'][$i]=0;
            }
            foreach($weekInfo as $item){
                if(in_array($item->time,$weeks['time'])){
                    $key = array_search($item->time,$weeks['time']);
                    $weeks['list'][$key] = 1;
                }
            }
        }else{
            $weeks['list'] = [];
        }
        $endTime = strtotime(date('Y-m-d 23:59:59',$time));
        $list = DB::table('calendar')
            ->where('owner_id',$uid)
            ->whereBetween('start_time', [$startTime,$endTime])
            ->select('id','name','position','resume_id as resumeId','step_name as stepName','address','interview_name as interviewName','start_time as startTime','end_time as endTime')
            ->orderBy('startTime','asc')
            ->get();
        $info = DB::table('staff')->where(['company_id'=>$userInfo->company_id,'mobile'=>$userInfo->mobile])->first();
        if(empty($list->toArray())){
           return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>['list'=>$list,'count'=>0,'name'=>$info->name,'weeks'=>$weeks['list']]]);
       }else{
           return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>['list'=>$list,'count'=>count($list),'name'=>$info->name,'weeks'=>$weeks['list']]]);
       }
    }
    /**
     * 紧凑日历列表
     * @param  $id    [用户ID]
     * @param  $return  json
     */
    
    public function calendarWeek(Request $request){
        $userInfo = $this->user;
        $uid = $userInfo->id;
//       $page = $this->page($request);
       $page = $request->input('page');
        if(!empty($page)){
            $timestamp = time()+$page*(7*24*3600);
        }else{
            $timestamp = time();
        }
      //本周开始时间
        $startTime = strtotime(date('Y-m-d', strtotime("this week Monday", $timestamp)));
        //本周结束时间
        $endTime = strtotime(date('Y-m-d', strtotime("this week Sunday", $timestamp))) + 24 * 3600 - 1  ;
       
        $list = DB::table('calendar')
            ->where('owner_id',$uid)
            ->whereBetween('start_time', [$startTime,$endTime])
            ->select('id','name','position','resume_id as resumeId','step_name as stepName','address','interview_name as interviewName',DB::raw("from_unixtime(start_time,'%W') as week"),'start_time as startTime','end_time as endTime')
            ->orderBy('endTime','asc')
            ->get();
        $weeks = [];
        foreach($list as $item){
            switch($item->week){
                case 'Monday':
                    $times = date('m月d日',$item->startTime).' 周一';
                    $ss['title'] = $times;
                    $ss['content'][] = $item;
                    if(empty($weeks[0])){
                        $weeks[0] = $ss;
                    }else{
                        $weeks[0]['content'][] = $item;
                    }
                    unset($ss['content']);
                    break;
                case 'Tuesday':
                    $times = date('m月d日',$item->startTime).' 周二';
                    $ss['title'] = $times;
                    $ss['content'][] = $item;
                    if(empty($weeks[1])){
                        $weeks[1] = $ss;
                    }else{
                        $weeks[1]['content'][] = $item;
                    }
                    unset($ss['content']);
                    break;
                case 'Wednesday':
                    $times = date('m月d日',$item->startTime).' 周三';
                    $ss['title'] = $times;
                    $ss['content'][] = $item;
                    if(empty($weeks[2])){
                        $weeks[2] = $ss;
                    }else{
                        $weeks[2]['content'][] = $item;
                    }
                    unset($ss['content']);
                    break;
                case 'Thursday':
                    $times = date('m月d日',$item->startTime).' 周四';
                    $ss['title'] = $times;
                    $ss['content'][] = $item;
                    if(empty($weeks[3])){
                        $weeks[3] = $ss;
                    }else{
                        $weeks[3]['content'][] = $item;
                    }
                    unset($ss['content']);
                    break;
                case 'Friday':
                    $times = date('m月d日',$item->startTime).' 周五';
                    $ss['title'] = $times;
                    $ss['content'][] = $item;
                    if(empty($weeks[4])){
                        $weeks[4] = $ss;
                    }else{
                        $weeks[4]['content'][] = $item;
                    }
                    unset($ss['content']);
                    break;
                case 'Saturday':
                    $times = date('m月d日',$item->startTime).' 周六';
                    $ss['title'] = $times;
                    $ss['content'][] = $item;
                    if(empty($weeks[5])){
                        $weeks[5] = $ss;
                    }else{
                        $weeks[5]['content'][] = $item;
                    }
                    unset($ss['content']);
                    break;
                case 'Sunday':
                    $times = date('m月d日',$item->startTime).' 周日';
                    $ss['title'] = $times;
                    $ss['content'][] = $item;
                    if(empty($weeks[6])){
                        $weeks[6] = $ss;
                    }else{
                        $weeks[6]['content'][] = $item;
                    }
                    unset($ss['content']);
                    break;
            }
        }
       sort($weeks);
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>['list'=>$weeks]]);
    }
    /**
     * 添加/修改日历
     * @param  $id    [用户ID]
     * @param  $return  json
     */
    public function addCalendar(Request $request){
        $infoId =  $request->input('flowHistoryId') ;
        $userInfo = $this->user;
        $uid = $userInfo->id;
        $timeInfo = DB::table('flow_histories')
            ->where('id',$infoId)
            ->first();
        $calInfo = DB::table('calendar')
            ->where([['info_id','=',$infoId],
                ['owner_id','=',$uid]])
            ->first();
        if(empty($calInfo)){
            $timeConflict = DB::select('select * FROM  calendar where NOT (end_time < ? or start_time > ?) and owner_id = ? ',[$timeInfo->stime,$timeInfo->etime,$uid]);
    
            Log::info('11'."@".$uid);
            if(!empty($timeConflict)){
                return  response()->json(['code'=>400,'msg'=>'时间冲突,日历添加失败','data'=>'']);
            }
            $reumes = DB::table('resumes')->where('id',$timeInfo->resume_id)->first();
            $result = DB::table('calendar')->insert(
                [   'info_id' => $infoId,
                    'owner_id'=>$uid,
                    'resume_id'=>$timeInfo->resume_id,
                    'name'=>$reumes->name,
                    'position'=>$reumes->position,
                    'step_name'=>$timeInfo->step_name,
                    'address'=>$timeInfo->address,
                    'interview_name'=>$timeInfo->owner_name,
                    'start_time' =>$timeInfo->stime,
                    'end_time'=>$timeInfo->etime,
                    'created_at'=>time(),
                    'updated_at'=>time()]
            );
        }else{
            if($uid == $calInfo->owner_id){
                $timeConflict = DB::select('select * FROM  calendar where NOT (end_time < ? or start_time > ?) and owner_id = ? ',[$timeInfo->stime,$timeInfo->etime,$uid]);
                Log::info('22'."@".$uid);
                if(!empty($timeConflict)){
                    return  response()->json(['code'=>400,'msg'=>'时间冲突,日历添加失败','data'=>'']);
                }
               $result =  DB::table('calendar')
                    ->where('info_id',  $infoId)
                    ->update(['start_time' => $timeInfo->stime,
                        'end_time'=>$timeInfo->etime,'updated_at'=>time()]);
            }else{
                $reumes = DB::table('resumes')->where('id',$timeInfo->resume_id)->first();
                $timeConflict = DB::select('select * FROM  calendar where NOT (end_time < ? or start_time > ?) and owner_id = ? ',[$timeInfo->stime,$timeInfo->etime,$uid]);
                Log::info('33'."@".$uid);
                if(!empty($timeConflict)){
                    return  response()->json(['code'=>400,'msg'=>'时间冲突,日历添加失败','data'=>'']);
                }
                $result = DB::table('calendar')->insert(
                    [   'info_id' => $infoId,
                        'owner_id'=>$uid,
                        'resume_id'=>$timeInfo->resume_id,
                        'name'=>$reumes->name,
                        'position'=>$reumes->position,
                        'step_name'=>$timeInfo->step_name,
                        'address'=>$timeInfo->address,
                        'interview_name'=>$timeInfo->owner_name,
                        'start_time' =>$timeInfo->stime,
                        'end_time'=>$timeInfo->etime,
                        'created_at'=>time(),
                        'updated_at'=>time()]
                );
            }
        }
        if($result){
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
        }
    }
}